package com.flong.lambda;

import org.junit.Test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @Author:liangjl
 * @Date: 2020/6/21-21:45
 * @Eamil:jilongliang@sina.com
 * @Description: 1、创建一个求和的任务
 */
public class ForkJoin {

    @Test
    public void testForkJoin() {

        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask task = new ForkJoinTask(1, 10000);

        Long result = forkJoinPool.invoke(task);
        System.out.println("result:" + result);
        long end = System.currentTimeMillis();

        System.out.println("消耗时间：" + (end - start));
    }
}

class ForkJoinTask extends RecursiveTask<Long> {

    //是否要拆分的临界值
    private static final long THRESHOLD = 3000;
    //起始值
    private final long start;
    //结束值
    private final long end;

    public ForkJoinTask(long start, long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {
        long length = end - start;
        if (length < THRESHOLD) {
            //计算
            long sum = 0;
            for (long i = start; i <= end; i++) {

                sum += i;
            }
            return sum;
        } else {
            //拆分
            long middle = (start + end) / 2;
            ForkJoinTask leftTask = new ForkJoinTask(start, middle);
            //进行fokr任务
            leftTask.fork();

            ForkJoinTask rightTask = new ForkJoinTask(middle + 1, end);
            rightTask.fork();

            return leftTask.join() + rightTask.join();

        }
    }

}

